package com.testdemo.common.view;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.testdemo.R;

/**
 * Created by joson on 2017/4/14.
 * 可清除的EditText
 */
public class ClearEditText extends LinearLayout{
    Context context;
    public EditText editText;
    public ImageView ivClean;

    public ClearEditText(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public ClearEditText(Context context, AttributeSet attrs) {
        super(context,attrs);
        this.context = context;
        init();
    }

    private void init() {
        View view =LayoutInflater.from(context).inflate(R.layout.view_clear_edittext,this);
        editText = (EditText) view.findViewById(R.id.et);
        ivClean = (ImageView) view.findViewById(R.id.iv_clean);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)){
                    ivClean.setVisibility(INVISIBLE);
                }else {
                    ivClean.setVisibility(VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        ivClean.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText("");
            }
        });


    }
}
